using UnityEditor;
using UnityEditor.Compilation;
using System;
using UnityEngine;
using System.Collections.Generic;

[InitializeOnLoad]
public class CompilationEventHandler
{
    [Obsolete]
    static CompilationEventHandler()
    {
        CompilationPipeline.assemblyCompilationStarted += OnCompilationStarted;
        CompilationPipeline.assemblyCompilationFinished += OnCompilationFinished;
    }

    private static List<CompilerMessage> compilerFailedMessages;

    private static void OnCompilationStarted(string assemblyPath)
    {
        compilerFailedMessages = new List<CompilerMessage>();
        Debug.Log("Compilation started for: " + assemblyPath);
        //HotUpdateManager.StopServer();
    }


    private static void OnCompilationFinished(string assemblyPath, CompilerMessage[] messages)
    {
        bool hasErrors = false;
        foreach (var message in messages)
        {
            if (message.type == CompilerMessageType.Error)
            {
                compilerFailedMessages.Add(message);
                hasErrors = true;
                break;
            } 
        }

        if (hasErrors)
        {
            Debug.Log("Compilation failed for: " + assemblyPath);
            string failedMassage = "";
            foreach (var message in compilerFailedMessages)
            {
                failedMassage += message.message + "\n";
            }
            Debug.Log("Compile failed :\n" + failedMassage);
            WebSocketClient.Say("Compile failed :\n" + failedMassage);
            // 执行需要在编译失败时运行的代码
        }
        else
        {
            Debug.Log("Compilation succeeded for: " + assemblyPath);
            // 执行编译成功后的代码
        }
    }
}
